package com.yq.cns.ui.main.fragment.news

import androidx.appcompat.resources.Compatibility
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yq.cns.net.NewsApiService
import com.yq.cns.ui.main.MainViewAction
import com.yq.cns.ui.main.MainViewState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlin.jvm.internal.Intrinsics

class NewsFragmentViewModel : ViewModel() {
    private val _viewState = MutableStateFlow<NewsFragmentState>(NewsFragmentState.Loading)
    val state: StateFlow<NewsFragmentState> = _viewState.asStateFlow()
    private val userIntent = MutableSharedFlow<NewsFragmentAction>()

    init {
        viewModelScope.launch {
            userIntent.collect {
                when (it) {
                    NewsFragmentAction.GetChannelData -> getChannelData()
                }
            }
        }

    }


    fun getChannelData() {
        _viewState.value = NewsFragmentState.Loading
        viewModelScope.launch(Dispatchers.IO) {
            kotlin.runCatching {
                NewsApiService.getChannelList().fullData()
            }.onSuccess {
                _viewState.value = NewsFragmentState.OnSuccess(it)
            }.onFailure {
                _viewState.value = NewsFragmentState.Fail(it.message)
            }
        }
    }

    fun dispatchEvent(getChannelData: NewsFragmentAction) {
        viewModelScope.launch {
            userIntent.emit(getChannelData)
        }
    }

}